package com.wiz.weixin.manager;

import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.wiz.weixin.VO.MPermanentVO;
import com.wiz.weixin.common.GlobalConstant;
import com.wiz.weixin.util.JSSDKUtil;

@Service("materialManager")
public class MaterialManager {
	private transient final Logger log = LoggerFactory.getLogger(getClass());
	private final String OBTAIN_PERMANENT_URL="https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN";
	
	/**
	 * 得到永久素材列表
	 * @param type 素材的类型
	 * @param offset 偏移位置
	 * @param count 返回数量
	 * @return
	 * @throws Exception 
	 */
	public JSONObject listPermanent(String type,int offset,int count) throws Exception{
		if(type == null || type.equals("")){
			log.error("listPermanent:type is null");
			throw new Exception("listPermanent:type is null");
		}
		
		String url = OBTAIN_PERMANENT_URL.replace("ACCESS_TOKEN", GlobalConstant.tencent_wx_token);
		MPermanentVO mpermanent = new MPermanentVO(type, offset, count);
		
		net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(mpermanent);
		log.info(jsonObject.toString());
		String response = JSSDKUtil.httpsRequest(url, "POST", jsonObject.toString());
		JSONObject responseJson = new JSONObject(response);
		if(!responseJson.isNull("errcode")){
			log.error(response.toString());
			throw new Exception(responseJson.getString("errmsg"));
		}
		log.info(responseJson.toString());
		return responseJson;
	}
}
